﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Beeldbankmvc.Models
{
    public class KeyWordRepository
    {
        BeeldbankLinqDataContext db = new BeeldbankLinqDataContext();

        public BeeldbankLinqDataContext GetDataContext()
        {
            return db;
        }
        
        public IQueryable<BEELDBANK_WORD> FindAllSorted(string letter)
        {
            return from p in FindAll()
                   where p.Word.StartsWith(letter)
                   orderby p.Word ascending
                   orderby p.Word
                   select p;
        }

        public IQueryable<BEELDBANK_WORD> FindAll()
        {
            return db.BEELDBANK_WORDs;
        }

        public BEELDBANK_WORD FindOne(int id)
        {
            return db.BEELDBANK_WORDs.SingleOrDefault(m => m.Id == id);
        }

        public void Add(BEELDBANK_WORD keyWord)
        {
            db.BEELDBANK_WORDs.InsertOnSubmit(keyWord);
        }

        public void Delete(BEELDBANK_WORD keyWord)
        {
            db.BEELDBANK_WORDs.DeleteOnSubmit(keyWord);
        }

        public void Save()
        {
            db.SubmitChanges();
        }

        public String UpdateStats(String keyWord)
        {
            return db.BEELDBANK_WORD_UPDATE_STATS_FROM_WORD(keyWord).ReturnValue.ToString();
        }
        
        internal List<String> FindKeyWords(string searchText, int maxResults)
        {
            var result = from n in FindAll()
                         where n.Word.StartsWith(searchText)
                         orderby n.Word
                         select n.Word;

            return result.Take(maxResults).ToList();
        }
    }
}